/**
 * Project Name:UIMS
 * File Name:UserAction.java
 * Package Name:com.bgi.uims.module.sys.User.action
 * CreateDate:2015年3月25日 上午10:19:52
 * Copyright (c) 2015, BGI_DX All Rights Reserved.
 */     

package com.bgi.uims.module.sys.user.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.bgi.uims.common.action.BaseAction;
import com.bgi.uims.common.dto.PageVo;
import com.bgi.uims.module.sys.department.dto.Department;
import com.bgi.uims.module.sys.department.service.DepartmentService;
import com.bgi.uims.module.sys.loginlog.dto.SysLoginlog;
import com.bgi.uims.module.sys.loginlog.service.SysLoginlogService;
import com.bgi.uims.module.sys.menu.service.MenuService;
import com.bgi.uims.module.sys.user.dto.Roles;
import com.bgi.uims.module.sys.user.dto.User;
import com.bgi.uims.module.sys.user.dto.UserLoginCount;
import com.bgi.uims.module.sys.user.service.UserService;
import com.bgi.uims.pub.utils.Constant;
import com.bgi.uims.pub.utils.PublicMethod;
import com.opensymphony.xwork2.ActionContext;


/**
 * ClassName:UserAction
 * Function: TODO 
 * Reason:	 TODO 
 * @CreateDate:2015年3月25日 上午10:19:52
 * @author   tantianhua
 * @version  
 * @since    JDK 1.7
 * @see 	 
 */
@Controller
@Scope("prototype")
public class UserAction extends BaseAction {
	
	/**  
	 * serialVersionUID:TODO（用一句话描述这个变量表示什么）  
	 */   
	private static final long serialVersionUID = -700919983611115341L;

	private PageVo pageVo = new PageVo();
	
	private User user;
	private Roles roles;

	private Integer[] page;

	private Integer[] rows;
	
	private String resText;
	
	@Resource
	private UserService userService;
	@Resource
	private DepartmentService departmentService;
	
	@Resource
	private SysLoginlogService sysLoginlogService;
	
	@Resource
	private MenuService menuService;

	public PageVo getPageVo() {
		return pageVo;
	}

	public void setPageVo(PageVo pageVo) {
		this.pageVo = pageVo;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public Roles getRoles() {
		return roles;
	}

	public void setRoles(Roles roles) {
		this.roles = roles;
	}
	

	public Integer[] getPage() {
		return page;
	}

	public void setPage(Integer[] page) {
		this.page = page;
	}

	public Integer[] getRows() {
		return rows;
	}

	public void setRows(Integer[] rows) {
		this.rows = rows;
	}
	
	public String getResText() {
		return resText;
	}

	public void setResText(String resText) {
		this.resText = resText;
	}

	/**
	 * @Description：  查询用户信息
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String findUser()
	{
		if(user==null)
		{
			user=new User();
		}
		user.getPage(this);
		pageVo=userService.queryUser(user);
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.SELECT,Constant.USERMODULES,user, null));
		pageVo.setSuccess(true);
		return SUCCESS;
	}
	
	/**
	 * @Description：  查询用户角色
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String queryUserRoles()
	{
		if(user==null)
		{
			user=new User();
		}
		user.getPage(this);
		pageVo=userService.queryUserRoles(user);
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.SELECT,Constant.USERMODULES,user, null));
		pageVo.setSuccess(true);
		return SUCCESS;
	}
	
	/**
	 * @Description：  查询单个用户信息
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String findUserById()
	{
		pageVo=new PageVo();
		pageVo.setObject(userService.findUserById(user));
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.SELECT,Constant.USERMODULES,user, null));
		pageVo.setSuccess(true);
		return SUCCESS;
	}
	
	/**
	 * @Description：  查询用户是否存在
	 * @author: liduo
	 * @version: V1.0
	 */
	public String isUserExist()
	{
		User userDb = userService.isUserExist(user);		
		if(userDb != null){
			if("0".equals(userDb.getAccountCount())){
				resText = "1";	
			  }else if("1".equals(userDb.getAccountCount())){
				resText = "2";	
			 }			
		  }else{
			resText = "0";
		 }		
		 return "resText";
	}	
	
	/**
	 * @Description：  保存用户信息
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String saveUser()
	{
		pageVo=new PageVo();
		if(user==null){
			pageVo.setSuccess(false);
			pageVo.setMsg("用户名称不允许为空!");
		}
		else
		{
			//获取登录的session
			User users=(User) session.get(Constant.LOGINUSER);
			if(user.getUserId()!=null&&!"".equals(user.getUserId())){
				User oldUser = userService.findUserById(user);
				Department department= new Department();
				department.setDepartmentId(oldUser.getDepartmentId());
				department = departmentService.queryDepartmentById(department);
				if(department != null){
					oldUser.setDepartmentName(department.getDepartmentName());
				}
				user.setLastModifiedUser(users.getRealName());
				pageVo=userService.saveUser(user);
				session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.UPDATE,Constant.USERMODULES , oldUser, user));
			}else{
				user.setAccountCount("1");
				user.setCreateUser(users.getRealName());
				pageVo=userService.saveUser(user);
				session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.INSERT,Constant.USERMODULES , user, null));

			}
 
			
		}
		return SUCCESS;
	}
	
	/**
	 * @Description：  删除用户信息
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String deleteUser(){
		pageVo=new PageVo();
		User oldUser = userService.findUserById(user);
		userService.deleteUserRoles(user);
		boolean f=  userService.deleteUser(user);
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.DELETE,Constant.USERMODULES , oldUser, user));
		pageVo.setSuccess(f);
		return SUCCESS;
	}
	
	/**
	 * @Description：  更新用户状态
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String updateUserStatus(){
		pageVo=new PageVo();
		User oldUser = new User();
		User newUser = new User();
		if("0".equals(user.getAccountCount())){
			
			oldUser.setUserId(user.getUserId());
			oldUser.setAccountCount("0");
			newUser.setUserId(user.getUserId());
			newUser.setAccountCount("1");
			user.setAccountCount("1");
			
		}
		else if("1".equals(user.getAccountCount())){
			
			oldUser.setUserId(user.getUserId());
			oldUser.setAccountCount("1");	
			newUser.setUserId(user.getUserId());
			newUser.setAccountCount("0");
			user.setAccountCount("0");
		}
		
		User users=(User) session.get(Constant.LOGINUSER);
		user.setLastModifiedUser(users.getRealName());
		pageVo.setObject(userService.updateUserStatus(user));
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.UPDATE,Constant.USERMODULES , oldUser, newUser));
		pageVo.setSuccess(true);
		return SUCCESS;
	}
	
	/**
	 * @Description：  查询角色
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	public String queryRolesId(){
		if(roles==null)
			roles=new Roles();
		pageVo=userService.queryRolesId(roles);
		session.put(Constant.OPERATIONMSG, PublicMethod.operationMsg(Constant.SELECT,Constant.USERMODULES,roles, null));
		pageVo.setSuccess(true);
		return SUCCESS;
	}
	//登陆
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String login(){
		// 如果已经登录,就不需要再次登录操作
		String type=SUCCESS;
		User sessionu = (User) session.get(Constant.LOGINUSER);
		if (sessionu == null || !sessionu.getUserName().equals(user.getUserName()))
		{
			// 如果上一用户还没有注销，采用新用户登录
			if (sessionu != null && !sessionu.getUserName().equals(user.getUserName())) {
				// 先注销session中的数据
				String log = (String) session.get(Constant.LOGINLOG_ID);
				if (log != null) {
					SysLoginlog loginlog = new SysLoginlog();
					loginlog.setLogId(log);
					sysLoginlogService.updateLoginLog(loginlog);
				}
				session.remove(Constant.LOGINLOG_ID);
				session.remove(Constant.DISABLEDRESOURCENAME);
				session.remove(Constant.DISABLEDRESOURCEURL);
				session.remove(Constant.LOGINUSER);
				// 注销掉Application中的
				ServletContext application = request.getSession().getServletContext();
				List sessions = (ArrayList) application.getAttribute(Constant.SESSIONS);
				if (sessions != null) {
					sessions.remove(session);
				}
			}
			// 登录
			if (user != null && user.getUserName() != null && user.getPassWord() != null && !"".equals(user.getUserName()) && !"".equals(user.getPassWord())) {
				// 存储日志
				SysLoginlog log = new SysLoginlog();
				log.setLoginIp(PublicMethod.getIpAddr(request));
				log.setUserName(user.getUserName());
				log.setBrowserMessage(PublicMethod.getBrowser(request));
				// 登录操作
				user = userService.login(user);
				log.setLoginResult(user.getQueryOneSql().substring(2, 3));//错误代码
				// if user is null,login fail
				if (!Constant.ERROR_CODE_101.equals(user.getQueryOneSql())) {
					//登录错误
					// 存储日志
					sysLoginlogService.savaLoginLog(log);//存储登陆日志
					request.setAttribute(Constant.ERRORINFO,user.getQueryOneSql());//错误代码
					type=ERROR;
				}
				else
				{
					//登录成功
					//存储日志
					//更新最后一次登录时间
					if(null != user.getUserId()){
						userService.updateUserLoginTime(user);
					}
					log.setWorkNumber(user.getWorkNumber()); 
					log.setRealName(user.getRealName());
					String logId=sysLoginlogService.savaLoginLog(log);//存储登陆日志
					log.setLogId(logId);
					user.setQueryOneSql(null);
					//加载未授权的资源
					//将name和url分开，name用于页面按钮置灰，url用于连接限制
					Set<String> actionNames = new HashSet<String>();
					Set<String> actionUrl = new HashSet<String>();
					PageVo pageData=menuService.disabledResource(user);
					if(pageData!=null&&pageData.getRows()!=null&&pageData.getRows().size()>0)
					{
						List<com.bgi.uims.module.sys.menu.dto.Resource> list=pageData.getRows();
						for (com.bgi.uims.module.sys.menu.dto.Resource res : list) {
							actionNames.add(res.getResourceName());
							actionUrl.add(res.getResourceUrl());
						}
					}
					session.put(Constant.DISABLEDRESOURCENAME,actionNames);
					session.put(Constant.DISABLEDRESOURCEURL,actionUrl);
					session.put(Constant.LOGINLOG_ID, log.getLogId());
					// 登录信息放入session
					session.put(Constant.LOGINUSER, user);
					// 登录信息放入Application监控在线用户
					Map application= ActionContext.getContext().getApplication();
					List sessions = (ArrayList) application.get(Constant.SESSIONS);
					if (sessions == null) {
						sessions = new ArrayList();
					}
					sessions.add(session);
					application.put(Constant.SESSIONS, sessions);
				}
			} else {
				//用户名或密码为空
				request.setAttribute(Constant.ERRORINFO,Constant.ERROR_CODE_101);
				type=ERROR;
			}
		}
		return type;
	}
	//注销
	@SuppressWarnings("rawtypes")
	public String logout() {
		String logId = (String) session.get(Constant.LOGINLOG_ID);
		if (logId != null) {
			SysLoginlog loginlog = new SysLoginlog();
			loginlog.setLogId(logId);
			sysLoginlogService.updateLoginLog(loginlog);
		}
		session.remove(Constant.DISABLEDRESOURCENAME);
		session.remove(Constant.DISABLEDRESOURCEURL);
		session.remove(Constant.LOGINLOG_ID);
		session.remove(Constant.LOGINUSER);
		// 注销掉Application中的
		Map application= ActionContext.getContext().getApplication();
		List sessions = (ArrayList) application.get(Constant.SESSIONS);
		if (sessions != null) {
			sessions.remove(session);
		}
		return SUCCESS;
	}
	
	/**
	 * @Description：  获取在线用户
	 * @author: tantianhua
	 * @CreateDate:2015年3月25日 上午10:19:52
	 * @version: V1.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String findOnlineUsers() {
		List<SysLoginlog> SysLoginlogList = new ArrayList<SysLoginlog>();
		Map application= ActionContext.getContext().getApplication();
		List sessions = (ArrayList) application.get(Constant.SESSIONS);
			if (sessions != null) {
				for (int i = (page[0] - 1) * rows[0]; i < page[0] * rows[0] && i < sessions.size(); i++) {
					Map<String, Object> sessionss = (Map<String, Object>) sessions.get(i);
					String logId = (String) sessionss.get(Constant.LOGINLOG_ID);
					SysLoginlog sysLoginlog = new SysLoginlog();
					sysLoginlog.setLogId(logId);
					sysLoginlog = sysLoginlogService.queryOneLoginlog(sysLoginlog);
					User users=(User) sessionss.get(Constant.LOGINUSER);
					sysLoginlog.setUserEmail(users.getUserEmail());
					sysLoginlog.setMobileNum(users.getMobileNum());	
					if (sysLoginlog != null) {
						SysLoginlogList.add(sysLoginlog);
					}
				}
				pageVo.setTotal(new Long(sessions.size()));
				pageVo.setRows(SysLoginlogList);
				pageVo.setSuccess(true);
			} else{
				pageVo.setTotal(new Long(0));
			}
		return SUCCESS;
	}
	
	/**
	 * 
	 * @Description：  统计当前年用户登录次数
	 * @author: wuyaohong
	 * @CreateDate:2015年4月2日 上午9:42:57
	 * @version: V1.0
	 */
	@SuppressWarnings("unchecked")
	public String getUserLoginCount(){
		pageVo = new PageVo();
		pageVo = userService.getUserLoginCount();
		List<UserLoginCount> counts = pageVo.getRows();
		String countData = "";
		for(UserLoginCount ulc : counts){
			countData += ulc.getCounts()+",";
		}
		countData = countData.substring(0, countData.length() - 1);
		pageVo.setObject(countData);
		pageVo.setSuccess(true);
		return SUCCESS;
	}
}
